package com.shen.JUC.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache cache = new MyCache();
        for (int i = 1; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                cache.setMap(temp + "", temp + "");
            }).start();
        }

        for (int i = 1; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                cache.getMap(temp + "");
            }).start();
        }

    }
}

//自动逸缓存
class MyCache {
    //读写锁:更加细粒度的控制
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private volatile Map<String, Object> map = new HashMap<>();


    public void setMap(String key, Object value) {//写，只有一个人可以写
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "write key" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "write key over");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void getMap(String key) {//读，可以多个人读
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "read key");
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "read key over");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }
    }
}
